<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车</title>
</head>

<body>
  <div id="root">
    <input type="checkbox" v-model="isall">
    <ul>
      <template v-for="(item,index) in carts">
        <li :key="item.id">
          <input type="checkbox" :value="item.id" v-model="ids">
          商品id：{{ item.id }} --
          商品名称：{{ item.name }} --
          商品数量：<button @click="decr(item,index)">---</button>{{ item.num }}<button @click="incr(item)">+++</button> --
          商品单价：{{ item.price }} --
          小计：{{ item.num * item.price }} --
          删除
        </li>
      </template>
    </ul>
    <div>
      总计：
      {{ total }}
    </div>
  </div>

  <script src="./js/vue.js"></script>
  <script>
    // 数据源，以后从后台得到
    var cartData = [
      {
        id: 1,
        name: '小米',
        price: 100,
        num: 1
      },
      {
        id: 2,
        name: '华为',
        price: 200,
        num: 1
      },
      {
        id: 3,
        name: '联想',
        price: 300,
        num: 1
      }
    ]

    new Vue({
      el: '#root',
      data: {
        carts: cartData,
        isall: false,
        ids: [],
        total: 0
      },
      watch: {
        isall(n, o) {
          let ids = []
          if(n){
            this.carts.forEach(item => ids.push(item.id))
          }
          this.ids = ids
        },
        carts: {
          handler(n, o) {
            let total = 0
            this.carts.forEach(item => {
              total += item.num * item.price
            })
            this.total = total
          },
          deep: true
        }
      },
      methods: {
        decr(item, index) {
          if (item.num > 1) {
            item.num--
          } else {
            // 短语运算
            confirm('您真的不去考虑购买一下吗?') && this.carts.splice(index, 1)
          }
        },
        incr(item) {
          item.num++
        }
      },
    })
  </script>


</body>

</html>